const { Controller } = require('egg');
const { error } = require('../utils/service');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    const { account, password } = ctx.request.body;

    const result = await this.app.mysql.get('user', { account, password });
    if (result) {
      ctx.session.username = result.username;
      ctx.session.account = account;
      ctx.session.password = password;
      ctx.body.content = { username: result.username };
    } else {
      throw error('账号或者密码错误', 400);
    }
  }

  async register() {
    const { ctx } = this;
    const { account, username, password } = ctx.request.body;

    const result = await this.app.mysql.get('user', { account });
    if (result) {
      throw error('该账号已存在！', 400);
    }
    await this.app.mysql.insert('user', { account, username, password });
  }

  async getUsername() {
    const { ctx } = this;
    const result = await this.app.mysql.get('user', { account: ctx.session.account });
    ctx.body.content = { username: result.username };
  }

  async getUserList() {
    const { ctx } = this;
    const { keyword } = ctx.request.body;
    let userList = [];
    if (keyword) {
      userList = await this.app.mysql.query(`select account,username from user where
      account like '${keyword}%' or username like '%${keyword}%'`);
    }
    ctx.body.content = userList;
  }
}

module.exports = UserController;
